<template>
	<view class="container">
		<form @submit="submitForm" class="form">
			<!-- 个人信息 -->
			<view class="infoBox">
				<!-- 姓名 -->
				<view class="formItem1">
					<text>{{ app.language.name }}:</text>
					<view class="formB">
						{{form.name}}
					</view>
				</view>
				<!-- 公民身份证号 -->
				<view class="formItem1">
					<text>{{ app.language.card }}:</text>
					<view class="formB">
						{{form.idcard}}
					</view>
				</view>
				<!-- 联系电话 -->
				<view class="formItem1">
					<text>{{ app.language.phone }}:</text>
					<view class="formB">
						{{form.phone}}
					</view>
				</view>
				<!-- 性别 -->
				<view class="formItem1">
					<text><text class="bt">*</text>{{ app.language.gender }}:</text>
					<view class="formB">
						<picker mode="selector" name="gender" :range="genderList"
							@change="onChangeCzGender(index, $event)">
							<view class="picker">
								{{selectedxbValue}}
							</view>
						</picker>
					</view>
				</view>
				<!-- 出生年月 -->
				<view class="formItem1">
					<text><text class="bt">*</text>{{ app.language.birth }}:</text>
					<view class="formB">
						<picker mode="date" :value="form.birth" :start="startDate" :end="endDate"
							@change="bindVisitingChange(index,$event)">
							<view class="uni-input qxz">{{form.birth}}</view>
						</picker>
					</view>
				</view>
				<!-- 民族 -->
				<view class="formItem1">
					<text><text class="bt">*</text>{{ app.language.nation }}:</text>
					<view class="formB">
						<picker mode="selector" name="nationality" :range="mzlist" @change="onMzChange">
							<view class="picker">
								{{selectedMzValue}}
							</view>
						</picker>
					</view>
				</view>
				<!-- 户籍所在派出所 -->
				<view class="formItem1">
					<text><text class="bt">*</text>{{ app.language.sldw }}:</text>
					<view class="formB">
						<picker mode="selector" name="pcs" :range="list" @change="onChange">
							<view class="picker">
								{{selectedValue}}
							</view>
						</picker>
					</view>
				</view>
				<!-- 原户籍地址 -->
				<view class="formItem1">
					<view>
						<text><text class="bt">*</text>{{ app.language.yhjdz }}:</text>
						<!-- 三级联动组件 -->
						<area-picker v-if="areaData.provinces.length > 0" :area-data="areaData"
							@change="handleFirstAreaChange" />
					</view>
				</view>
				<!-- 现居住地址 -->
				<view class="formItem1">
					<text><text class="bt">*</text>{{ app.language.xhjdz }}:</text>
					<!-- 三级联动组件 -->
					<area-picker v-if="areaData.provinces.length > 0" :area-data="areaData"
						@change="handleSecondAreaChange" />
				</view>
				<!-- 几号楼几单元几层几号房 -->
				<view class="formItem1">
					<text><text class="bt">*</text>{{ app.language.jhl }}:</text>
					<view class="formB">
						<input type="text" v-model="form.adressmessage" :placeholder="app.language.ijhl" />
					</view>
				</view>
				<!-- 原因 -->
				<view class="formItem1">
					<text><text class="bt">*</text>{{ app.language.shuoming }}:</text>
					<view class="formC">
						<input type="textarea" v-model="form.applyreason" :placeholder="app.language.ishuoming" />
					</view>
				</view>
			</view>

			<view class="infoBox1">
				<!-- 居民身份证 -->
				<h2 class="title">所需材料：</h2>
				<view class="formItem">
					<text><text class="bt">*</text>{{ app.language.sfzzfm }}:</text>
					<view class="hjbImg">
						<button type="default" @click="chooseImg(1)">{{ app.language.scimg }}</button>
					</view>
					<view class="scimageBox" v-if="jmsfzImg.length>0">
						<view class="del" @click="delImg(jmsfzImg,1)">
							<image class="delImg" src="/static/dels.png"></image>
						</view>
						<image class="scimage" :src="imgUrl+item" v-for="(item,index) in jmsfzImg" :key='index'
							@click="previewImg(item)"></image>
					</view>
				</view>
				<!-- 房屋租赁合同或务工劳务合同 -->
				<view class="formItem">
					<text><text class="bt">*</text>{{ app.language.htName }}:</text>
					<view class="hjbImg">
						<button type="default" @click="chooseImg(2)">{{ app.language.scimg }}</button>
					</view>
					<view class="scimageBox" v-if="htImg.length>0">
						<view class="del" @click="delImg(htImg,2)">
							<image class="delImg" src="/static/dels.png"></image>
						</view>
						<image class="scimage" :src="imgUrl+item" v-for="(item,index) in htImg" :key='index'
							@click="previewImg(item)"></image>
					</view>
					<!-- <image class="scimage" :src="item" v-for="(item,index) in swtdsImg" :key='index' @click="previewImg(item)"></image> -->
				</view>
				<!-- 房东居民身份证 -->
				<view class="formItem">
					<text><text class="bt">*</text>{{ app.language.fdText }}:</text>
					<view class="hjbImg">
						<button type="default" @click="chooseImg(3)">{{ app.language.scimg }}</button>
					</view>
					<view class="scimageBox" v-if="fdImg.length>0">
						<view class="del" @click="delImg(fdImg,3)">
							<image class="delImg" src="/static/dels.png"></image>
						</view>
						<image class="scimage" :src="imgUrl+item" v-for="(item,index) in fdImg" :key='index'
							@click="previewImg(item)"></image>
					</view>
					<!-- <image class="scimage" :src="item" v-for="(item,index) in qtswclImg" :key='index' @click="previewImg(item)"></image> -->
				</view>
			</view>
			<button @click="getAdd" class="submit">提交</button>
		</form>
	</view>
</template>

<script>
	import graceChecker from "../../components/graceChecker.js"
	import {
		getPcsList,
		getHjsx,
		getBlsx,
		getJgSq,
		getNationality,
		geAgent
	} from '@/api/api.js'
	import {
		getAddResidencePermit
	} from '@/api/domicile.js'
	import config from '@/config'
	import {
		fetchAndProcessAreaData
	} from '@/api/processCountryData.js';
	import AreaPicker from '@/components/areapicker.vue';
	const global = getApp().globalData;
	export default {
		components: {
			AreaPicker
		},
		data() {
			return {
				imgUrl: config.baseUrl,
				app: {
					global: global,
					name: global.appName,
					language: global.language
				},
				name: "",
				form: {
					name: "李会会",
					idcard: "620524199712201463",
					phone: "",
					nationality: "",
					agent: "",
					birth: "",
					chooseImags: [],
				},
				hjsxList: [],
				id: "",
				token: "",
				pcsList: [],
				Hjxslists: [],
				hjsxList: [],
				blsxLists: [],
				xhjsxList: [],
				list: [],
				// / 派出所
				selectedHjsxValue: '',
				selectedXhjdzValue: '',
				selectedValue: "",

				// 民族列表
				mzlist: [],
				ChuzMzList: [],
				selectedMzValue: "",
				// 性别
				selectedxbValue: "",
				selectecsnybValue: "",

				// 图片列表
				jmsfzImg: [],
				htImg: [],
				fdImg: [],
				genderList: [],
				xingbieList: [],
				areaData: {
					provinces: [],
					cities: {},
					areas: {}
				}

			}
		},
		async onLoad(options) {
			uni.showLoading({
				title: this.app.language.jzz,
			});
			this.id = options.id
			this.form.handlingMatters = options.id
			this.selectedHjsxValue = this.app.language.qxz
			this.selectedXhjdzValue = this.app.language.qxz
			this.selectedValue = this.app.language.qxz
			this.selectedMzValue = this.app.language.qxz
			this.selectedxbValue = this.app.language.qxz
			this.form.birth = this.app.language.qxz
			this.getPcs();
			this.getblsx();
			this.getMzList();
			this.getagent()
			this.areaData = await fetchAndProcessAreaData();
			this.loadAreaData();
			this.getToken();
		},
		methods: {
			async loadAreaData() {
				uni.showLoading({
					title: this.app.language.jzz
				});

				try {
					const data = await fetchAndProcessAreaData();
					if (data) {
						this.areaData = data;
					}
					// else {
					// 	uni.showToast({
					// 		title: '加载地区数据失败',
					// 		icon: 'none'
					// 	});
					// }
				} catch (error) {
					console.error('加载地区数据出错:', error);
					// uni.showToast({
					// 	title: '加载地区数据出错',
					// 	icon: 'none'
					// });
				} finally {
					uni.hideLoading();
				}
			},
			// 三级联动
			handleFirstAreaChange(selected) {
				// this.firstSelectedArea = selected;
				console.log('第一个选择器选择:', selected);
				this.selectedHjsxValue = selected.fullText
				this.form.adress = selected.fullText
			},
			handleSecondAreaChange(selected) {
				// this.secondSelectedArea = selected;
				console.log('第二个选择器选择:', selected);
				this.selectedXhjdzValue = selected.fullText
				this.form.addressnow = selected.fullText
			},
			// 获取缓存
			getToken() {
				let that = this
				uni.getStorage({
					key: 'loginData',
					success: function(res) {
						console.log('缓存', res)
						that.form.reportType = res.data.userInfo.peopleType
						that.token = res.data.userInfo.appToken
						that.userInfo = res.data.userInfo
						that.form.phone = res.data.userInfo.phonenumber
						uni.hideLoading();
					}
				});
			},

			// 获取派出所列表
			getPcs() {
				let data = {
					"": ""
				}
				getPcsList(data).then((res) => {
					this.pcsList = res.data
					console.log('res.data', res.data)
					if (res.code == 200) {
						for (let i = 0; i < res.data.length; i++) {
							this.list.push(res.data[i].deptName);
						}
					}
				})
			},

			// 获取办理事项
			getblsx() {
				let data = {
					"": ""
				}
				getBlsx(data).then((res) => {
					if (res.code == 200) {
						this.blsxLists = res.rows
						this.name = "居住证办理"
					}
				})
			},


			// 获取名族列表
			getMzList() {
				getNationality().then((res) => {
					this.ChuzMzList = res.rows
					for (let i = 0; i < res.rows.length; i++) {
						this.mzlist.push(res.rows[i].dictLabel);
					}
				})
			},

			// 选择派出所
			onChange(e) {
				this.selectedValue = this.list[e.detail.value];
				this.form.policestation = this.pcsList[e.detail.value].deptId;
			},


			// 获取性别列表
			getagent() {
				uni.showLoading({
					title: this.app.language.jzz,
				});
				geAgent().then((res) => {
					this.xingbieList = res.rows
					for (let i = 0; i < res.rows.length; i++) {
						this.genderList.push(res.rows[i].dictLabel);
						uni.hideLoading();
					}
				})
			},

			// 选择性别
			onChangeCzGender(index, e) {
				this.selectedxbValue = this.genderList[e.detail.value];
				this.form.agent = this.xingbieList[e.detail.value].dictValue;
			},

			// 来访时间
			bindVisitingChange: function(index, e) {
				this.form.birth = e.detail.value
			},

			// 民族
			onMzChange(e) {
				this.selectedMzValue = this.ChuzMzList[e.detail.value].dictLabel;
				this.form.nationality = this.ChuzMzList[e.detail.value].dictValue;
			},

			// 上传图片
			chooseImg(item) {
				this.imgId = item
				uni.chooseImage({
					count: 5,
					success: (res) => {
						this.srcImg = res.tempFilePaths

						let tempFilePaths = res.tempFilePaths;
						// this.tempFilePathList = res.tempFilePaths;
						let base64List = this.form.chooseImags;
						// 图片路径转换成base64格式
						tempFilePaths.forEach((item, index) => {
							uni.getFileSystemManager().readFile({
								filePath: item, // 图片文件路径
								encoding: 'base64', // 编码格式为base64
								success: res => { // 成功回调
									let base64 = 'data:image/jpeg;base64,' + res
										.data; // 拼接data URI
									base64List.push(base64);
									if (base64List.length === tempFilePaths.length) {
										this.form.chooseImags = base64List;
									}
								},
								fail: err => {
									console.error('读取文件失败', err);
								}
							});
						});

						// 上传图片并返回路径
						let imgList = [];
						// 上传前显示加载中
						uni.showLoading({
							title: this.app.language.jzz,
						});
						tempFilePaths.forEach((tempFilePaths) => {
							const uploadTask = uni.uploadFile({
								url: 'https://mqzhian.cn:8088/common/upload', // 你的ThinkPHP服务器地址
								filePath: tempFilePaths,
								name: 'file', // 这里根据服务器接收的字段来定义
								success: (uploadFileRes) => {
									const data = JSON.parse(uploadFileRes.data);
									console.log('上传成功', data);
									// 上传成功后隐藏加载中
									uni.hideLoading();
									imgList.push(data.fileName);
									if (item == 1) {
										this.jmsfzImg = imgList
										this.form.idcardphoto = imgList.join(',')
									} else if (item == 2) {
										this.htImg = imgList
										this.form.contract = imgList.join(',')
									} else if (item == 3) {
										this.fdImg = imgList
										this.form.landlordphoto = imgList.join(',')
									}
								},
								fail: (error) => {
									console.error('上传失败', error);
									uni.showToast({
										title: '上传失败',
										icon: 'none',
									});
								}
							});
						});
					}
				})
			},

			// 删除图片
			delImg(list, id) {
				console.log('id', id)
				console.log('list', list)
				uni.showModal({
					title: '确认删除', // 弹框标题
					content: '确定要删除这组图片吗？', // 弹框内容
					cancelText: '取消', // 取消按钮文本
					confirmText: '确定', // 确认按钮文本
					success: (res) => {
						if (res.confirm) {
							// 用户点击了“确定”按钮
							if (id == 1) {
								this.jmsfzImg = []
							} else if (id == 2) {
								this.htImg = []
							} else if (id == 3) {
								this.fdImg = []
							}
						} else if (res.cancel) {
							// 用户点击了“取消”按钮，或者关闭了弹框
							console.log('用户取消删除');
						}
					}
				});
			},

			// 提交
			getAdd() {
				if (!this.selectedxbValue || this.selectedxbValue === this.app.language.qxz) {
					uni.showToast({
						title: this.app.language.Igender,
						icon: 'none',
					});
					return
				}
				if (!this.form.birth || this.form.birth === this.app.language.qxz) {
					uni.showToast({
						title: this.app.language.csrq_idate,
						icon: 'none',
					});
					return
				}

				if (!this.selectedMzValue || this.selectedMzValue === this.app.language.qxz) {
					uni.showToast({
						title: this.app.language.ination,
						icon: 'none',
					});
					return
				}
				if (!this.selectedValue || this.selectedValue === this.app.language.qxz) {
					uni.showToast({
						title: this.app.language.hjpcsTx,
						icon: 'none',
					});
					return
				}
				if (!this.selectedHjsxValue || this.selectedHjsxValue === this.app.language.qxz) {
					uni.showToast({
						title: this.app.language.iyhjdz,
						icon: 'none',
					});
					return
				}
				if (!this.selectedXhjdzValue || this.selectedXhjdzValue === this.app.language.qxz) {
					uni.showToast({
						title: this.app.language.ixhjdz,
						icon: 'none',
					});
					return
				}
				if (!this.form.adressmessage) {
					uni.showToast({
						title: this.app.language.jhls,
						icon: 'none',
					});
					return
				}
				if (!this.form.applyreason) {
					uni.showToast({
						title: this.app.language.shuomings,
						icon: 'none',
					});
					return
				}
				if (this.jmsfzImg.length == 0) {
					uni.showToast({
						title: this.app.language.icards,
						icon: 'none',
					});
					return
				}
				if (this.htImg.length == 0) {
					uni.showToast({
						title: this.app.language.ihtName,
						icon: 'none',
					});
					return
				}
				if (this.fdImg.length == 0) {
					uni.showToast({
						title: this.app.language.ifdText,
						icon: 'none',
					});
					return
				}

				uni.showLoading({
					title: this.app.language.jzz,
				});
				this.form.appToken = this.token
				getAddResidencePermit(this.form).then((res) => {
					if (res.code == 200) {
						uni.hideLoading();
						uni.showToast({
							title: this.app.language.qddsh,
							icon: 'success',
						});
						setTimeout(() => {
							console.log('跳转首页')
							uni.reLaunch({
								url: '/pages/bmfw/listText'
							});
						}, 1000);
					}
				})
			}
		}

	}
</script>

<style>
	.container {
		padding: 20rpx;
	}

	.form {
		box-shadow: 1px 1px 10rpx #ddd;
		/* display: block; */
		width: 100%;
		padding-bottom: 20rpx;
	}

	.formItem {
		margin: 10rpx 0;
		padding: 10rpx;
		/* height: 162rpx; */
		position: relative;
		border-bottom: 1px dashed #ddd
	}

	.infoBox {
		border: 1px solid #ddd;
		padding: 0 20rpx;
		box-shadow: 1px 1px 10rpx #ddd;
	}

	.infoBox1 {
		border: 1px solid #ddd;
		margin-top: 20rpx;
		padding: 0 15rpx;
		box-shadow: 1px 1px 10rpx #ddd;
	}

	.formItem1 {
		margin: 10rpx 0;
		padding: 10rpx;
		/* height: 162rpx; */
		position: relative;
		border-bottom: 1px dashed #ddd
	}

	.formB {
		/* background-color: #f3f3f3; */
		font-size: 24rpx;
		padding: 10rpx;
		margin-top: 10rpx;
		position: absolute;
		right: 10rpx;
		top: -2rpx;
		text-align: right;
		color: #808080;
	}

	.formC {
		font-size: 24rpx;
		padding: 10rpx;
		margin-top: 10rpx;
		border: 1px solid #ddd;
		height: 117rpx;
	}

	.formItem text,
	.formItem1 text {
		font-size: 26rpx;
	}

	.hjbImg button {
		font-size: 22rpx;
		width: 149rpx;
		height: 56rpx;
		background: #2f8ef9;
		color: #fff;
	}

	.hjbImg {
		/* position: absolute;
		bottom: 10rpx; */
		width: 150rpx;
		margin-top: 20rpx;
	}

	.scimageBox {
		display: inline-block;
		width: 100%;
		height: 100rpx;
		position: relative;
		/* text-align: center; */
	}

	.scimage {
		width: 121rpx;
		height: 80rpx;
		margin-right: 10rpx;
		margin-top: 5px;
		border-radius: 5rpx;
	}

	.title {
		margin-top: 30rpx;
		font-weight: bold;
		font-size: 28rpx;
	}

	.submit {
		background-color: #2f8ef9;
		color: #fff;
		font-size: 28rpx;
		width: 95%;
		margin: 20rpx auto 0;
	}

	.picker {
		padding: 10px;
		text-align: right;
		margin-top: -25rpx;
	}

	.bt {
		color: red;
		margin-right: 5rpx;
	}

	.picker {
		width: 260rpx;
		color: #808080;
	}

	.del {
		color: red;
		font-size: 26rpx;
		text-align: right;
		width: 50rpx;
		height: 50rpx;
		position: absolute;
		right: 0;
		top: -43rpx;
	}

	.delImg {
		width: 50rpx;
		height: 50rpx;
	}

	.qxz {
		position: relative;
		right: 21rpx;
		color: #808080;
	}
</style>